package cn.xiaoyu.su.service.impl;

import cn.xiaoyu.su.controller.request.TrafficPageRequest;
import cn.xiaoyu.su.enums.EventMessageType;
import cn.xiaoyu.su.feign.ProductFeignService;
import cn.xiaoyu.su.interceptor.LoginInterceptor;
import cn.xiaoyu.su.manager.TrafficManager;
import cn.xiaoyu.su.model.EventMessage;
import cn.xiaoyu.su.model.TrafficDO;
import cn.xiaoyu.su.service.TrafficService;
import cn.xiaoyu.su.util.JsonData;
import cn.xiaoyu.su.util.JsonUtil;
import cn.xiaoyu.su.vo.ProductVO;
import cn.xiaoyu.su.vo.TrafficVO;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ⼆当家⼩D
 * @since 2022-10-27
 */
@Service
@Slf4j
public class TrafficServiceImpl  implements TrafficService {
    @Autowired
    private TrafficManager trafficManager;

    @Autowired
    private ProductFeignService productFeignService;

    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void handleTrafficMessage(EventMessage eventMessage) {

        Long accountNo = eventMessage.getAccountNo();

        String messageType = eventMessage.getEventMessageType();
        if (EventMessageType.PRODUCT_ORDER_PAY.name().equalsIgnoreCase(messageType)){

            //订单已经支付，新增流量包

            String content = eventMessage.getContent();
            Map<String,Object> orderInfoMap = JsonUtil.json2Obj(content,Map.class);

            String outTradeNo = (String)orderInfoMap.get("outTradeNo");
            Integer buyNum = (Integer) orderInfoMap.get("buyNum");
            String productStr = (String) orderInfoMap.get("product");
            ProductVO productVO = JsonUtil.json2Obj(productStr, ProductVO.class);
            log.info("商品信息:{}",productVO.toString());

            //流量包有效期
            LocalDateTime expiredDateTime = LocalDateTime.now().plusDays(productVO.getValidDay());
            Date date = Date.from(expiredDateTime.atZone(ZoneId.systemDefault()).toInstant());

            //构建流量包对象
            TrafficDO trafficDO = TrafficDO.builder()
                    .accountNo(accountNo)
                    .dayLimit(productVO.getDayTimes() * buyNum)
                    .dayUsed(0)
                    .totalLimit(productVO.getTotalTimes())
                    .pluginType(productVO.getPluginType())
                    .level(productVO.getLevel())
                    .productId(productVO.getId())
                    .outTradeNo(outTradeNo)
                    .expiredDate(date).build();

            int rows = trafficManager.add(trafficDO);
            log.info("消费消息新增流量包：rows={},trafficDO={}",rows,trafficDO);

        } else if (EventMessageType.TRAFFIC_FREE_INIT.name().equalsIgnoreCase(messageType)){
            //发放免费流量包
            Long productId = Long.valueOf(eventMessage.getBizId());

            JsonData jsonData = productFeignService.detail(productId);
            ProductVO productVO = jsonData.getData(new TypeReference<ProductVO>(){});

            //构建流量包对象
            TrafficDO trafficDO = TrafficDO.builder()
                    .accountNo(accountNo)
                    .dayLimit(productVO.getDayTimes())
                    .dayUsed(0)
                    .totalLimit(productVO.getTotalTimes())
                    .pluginType(productVO.getPluginType())
                    .level(productVO.getLevel())
                    .productId(productVO.getId())
                    .outTradeNo("free_init")
                    .expiredDate(new Date()).build();

            trafficManager.add(trafficDO);
        }

    }

    /**
     * 分页查询可用流量包
     * @param request
     * @return
     */
    @Override
    public Map<String, Object> pageAvailable(TrafficPageRequest request) {

        int page = request.getPage();
        int size = request.getSize();

        long accountNo = LoginInterceptor.threadLocal.get().getAccountNo();

        IPage<TrafficDO> pageResult = trafficManager.pageAvailable(page, size, accountNo);

        Map<String,Object> map = new HashMap<>(3);

        map.put("total_record",pageResult.getTotal());
        map.put("total_page",pageResult.getPages());
        map.put("current_record",pageResult.getRecords().stream().map(obj->beanProcess(obj)).collect(Collectors.toList()));

        return map;
    }

    /**
     * 查询流量包详情
     * @param trafficId
     * @return
     */
    @Override
    public TrafficVO detail(Long trafficId) {

        long accountNo = LoginInterceptor.threadLocal.get().getAccountNo();

        TrafficDO trafficDO = trafficManager.findByIdAndAccountNo(trafficId,accountNo);

        return beanProcess(trafficDO);
    }

    /**
     * 删除过期流量包
     * @return
     */
    @Override
    public boolean deleteExpiredTraffic() {
        return trafficManager.deleteExpiredTraffic();
    }

    private TrafficVO beanProcess(TrafficDO trafficDO){
        TrafficVO trafficVO = new TrafficVO();
        BeanUtils.copyProperties(trafficDO,trafficVO);
        return trafficVO;
    }
}
